package cn.fz.jpademo01.service.impl;

import cn.fz.jpademo01.domain.entity.SysUser;
import cn.fz.jpademo01.repo.SysUserRepository;
import cn.fz.jpademo01.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl implements SysUserService {
    private final SysUserRepository userRepository;

    @Override
    public Page<SysUser> page(Pageable pageable) {
        return null;
    }

    @Override
    public List<SysUser> list() {
        return userRepository.findAll();
    }

    @Override
    public SysUser retrieve(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @Override
    public SysUser findByUsername(String username) {
        // 使用基于方法名定义的查询
        // return userRepository.findByUsername(username).orElse(null);
        // 使用基于@Query定义的查询
        // return userRepository.findByUsername2(username).orElse(null);
        // 使用Specification查询
        return userRepository.findOne(
                (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("username").as(String.class), username)
        ).orElse(null);
    }

    @Override
    public SysUser create(SysUser user) {
        return userRepository.save(user);
    }

    @Override
    public SysUser update(SysUser user) {
        if (userRepository.findById(user.getId()).isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        return userRepository.save(user);
    }

    @Override
    public void remove(List<Long> ids) {
        userRepository.deleteAllById(ids);
    }
}
